<?php

namespace App\Models\Oauth;

use Illuminate\Support\Facades\DB;
use App\Models\Model;
use App\Core\Utils\TwHelper\CommFunction;


/**
 * 短信验证码表模型
 */
class SendCodeModel extends Model
{

    const TABLENAME = 'tw_base_send_code';

    /**
     * 已使用
     */
    const IS_USED = 1;

    /**
     * 未使用
     */
    const NO_USED = 0;


    /**
     * 初始化并返回数据库请求构建器
     *
     * @return Illuminate\Support\Facades\DB::table(TABLENAME)
     */
    public static function dbTable()
    {
        return DB::table(self::TABLENAME);
    }

    /**
     * 添加
     */
    public static function addCode($mobile, $code)
    {
        $data = array();
        $data['mobile'] = $mobile;
        $data['code'] = $code;
        $data['year'] = date('Y', time());
        $data['month'] = date('m', time());
        $data['day'] = date('d', time());
        $data['created'] = time();
        $data['ip'] = CommFunction::getip();
        $data['used'] = self::NO_USED;
        return self::dbTable()->insertGetId($data);
    }

    public static function getCount($where)
    {
        //$where[] = ['mobile','=','13881119539'];
        // $where[] = ['created', '>', CommFunction::getDawnTime()];
        return self::dbTable()->where($where)->count();
    }

    /**
     * 验证验证码
     */
    public static function checkCode($mobile, $code)
    {
        $where = array();
        $where[] = ['year', '=', date('Y', time())];
        $where[] = ['month', '=', date('m', time())];
        $where[] = ['day', '=', date('d', time())];
        $where[] = ['mobile', '=', $mobile];
        $where[] = ['code', '=', $code];
        $where[] = ['used', '=', self::NO_USED];
        return self::dbTable()->where($where)->first();
    }

    /**
     * 查询验证码
     */
    public static function getCodeData($mobile)
    {
        $where = array();
        $where[] = ['year', '=', date('Y', time())];
        $where[] = ['month', '=', date('m', time())];
        $where[] = ['day', '=', date('d', time())];
        $where[] = ['mobile', '=', $mobile];
        $where[] = ['used', '=', self::NO_USED];
        return self::dbTable()->where($where)->orderBy('id', 'desc')->first();
    }

    /**
     * 使用验证码
     */
    public static function usedCode($code, $mobile)
    {
        $where = array();
        $where[] = ['year', '=', date('Y', time())];
        $where[] = ['month', '=', date('m', time())];
        $where[] = ['day', '=', date('d', time())];
        $where[] = ['mobile', '=', $mobile];
        $where[] = ['code', '=', $code];
        $updateDate['used'] = self::IS_USED;
        return self::dbTable()->where($where)->update($updateDate);
    }

}

?>